import { h, type Ref } from 'vue'
import tinycolor, { type ColorFormats } from 'tinycolor2'
import type { Color } from './graphic'

export function createCanvas(el: Ref<HTMLCanvasElement>) {
  let _ctx: CanvasRenderingContext2D | null
  function getCtx2d() {
    if (!_ctx) {
      _ctx = el.value.getContext('2d')
    }
    return _ctx
  }
  // function PutPixel(x: number, y: number, color: Color) {
  //   const ctx = getCtx2d()
  //   if (ctx) {
  //     ctx.fillStyle = color
  //     ctx.fillRect(x, y, 1, 1)
  //   }
  // }
  // function Draw(width: number, height: number, traceColor: (x: number, y: number) => Color) {
  //   for (let x = -width / 2; x < width; x++) {
  //     for (let y = -height / 2; y < height; y++) {
  //       PutPixel(x, y, traceColor(x, y))
  //     }
  //   }
  // }
  function DrawWidthImageData(
    width: number,
    height: number,
    traceColor: (x: number, y: number) => Color
  ) {
    const ctx = getCtx2d()
    if (!ctx) return
    const imageData = ctx.createImageData(width, height)
    for (let x = 0; x < width; x++) {
      for (let y = 0; y < height; y++) {
        const index = (x + y * width) * 4
        const [r, g, b, a] = traceColor(x, y)
        imageData.data[index] = r
        imageData.data[index + 1] = g
        imageData.data[index + 2] = b
        imageData.data[index + 3] = a * 255
      }
    }
    ctx.putImageData(imageData, 0, 0)
  }
  return {
    // PutPixel,
    DrawView: DrawWidthImageData
  }
}
